<?php
/**
 * Created by PhpStorm.
 * User: hjc_0
 * Date: 2016/11/30
 * Time: 22:57
 */

class HduOauthInterf extends UserOauthBaseInterf
{
    const CALL_HOST = 'http://wywx.hdu.edu.cn';
    private $accountId; //企业账号
    private $sn;    //学号

    /**
     * 两个对象间复制属性值 ，当一个属性在两边都存在时才复制
     * 属性值是NULL也会复制
     *
     * @param mixed $src 数据源，数组|对象
     * @param string $des 目标数据
     * @return Object 返回对象本身
     */
    public function setProperties($src)
    {
        $src_vars = is_object($src) ? get_object_vars($src) : $src;
        foreach ($src_vars as $name => $value) {
            if (property_exists($this, $name)) {
                $this->$name = $value;
            }
        }

        return $this;
    }

    /**
     * 调用接口的核心接口
     * @return array|boolen|resource
     */
    public function callOauthIntf()
    {
        import('ORG.Http');
        $url = self::CALL_HOST.'/interface/authApi/getUserInfo';
        $res = Http::curlPost($url,array('staffId'=>$this->sn,'accessToken'=>session('api_access_token')));
        $res = json_decode($res,true);
        $returnData = $this->doCallBack($res);
        return $returnData;
    }

    /**
     * 回调操作将用户入库
     * @param array $callRes    访问的结果
     * @throws Exception
     */
    public function doCallBack($callRes)
    {
        if ($callRes['STAFFTYPE'] < 3) {
            $userType = 0;
        } else {
            $userType = 1;
        }

        $data = array(
            'account_id' => $this->accountId,
            'type' => $userType,
            'real_name' => $callRes['STAFFNAME'],
            'number' => $callRes['STAFFID'],
            'avatar' => session('headimgurl'),
            'status' => 2,
            'sex' => 0,
            'mobile' => ''
        );

        $info = D('Base/User')->getInfo(array('number'=>$data['number'],'type'=>array('in',array(0,1))));
        if(!$info){
            $info = D('Base/User')->update($data);
        }
        if($info['status'] == 0){
            $info = D('Base/User')->update(array('user_id'=>$info['user_id'],'status'=>2));
        }

        session('userId',$info['user_id']);

        if(session('wechatUserId')){
            $condition = array(
                            'wechat_user_id'    =>  session('wechatUserId'), 
                            'user_id'           =>  $info['user_id']
                            );
            M('WechatUser')->update($condition);
        }
        
        return $res;
    }

}